<template>
  <div class="container">
    <van-nav-bar
        title="历史对话"
        left-text=""
        right-text=""
    >
      <template #right>
        <van-icon name="add-o"
                  size="24"
                  @click="handleHistoryAddClick"/>
      </template>
    </van-nav-bar>
    <div class="history-list">
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="仅展示最近十条对话"
          @load="loadData"
      >
        <van-cell
            v-for="item in historyList"
            :key="item"
            clickable
            class="history-item"
            :title="item.title"
            :label="moment(item.createdTime).format('YYYY-MM-DD HH:mm:ss')"
            @click="handleHistoryClick(item,$event)"
        >
          <template #right-icon>
            <van-icon name="cross" class="delete-icon" @click="handleDelete(item)"/>
          </template>
        </van-cell>
      </van-list>
    </div>
  </div>
</template>
<script setup lang="ts">
import {AppApi} from '@/api'
import {onMounted, ref} from 'vue'
import {showConfirmDialog,showFailToast} from 'vant'
import moment from 'moment';


const historyList = ref<any[]>([])
const finished = ref(false)
const loading = ref(false)

const {appId} = defineProps({appId: String})
const emit = defineEmits(['add', 'clickItem'])
const loadData = () => {
  if (!appId) {
    return
  }
  AppApi.getChatHistory(appId).then((res: any) => {
    historyList.value = res
    finished.value = true
    loading.value = false
  })
}
const handleHistoryClick = (item: any,event: any) => {
  if (event.target.className.indexOf('delete-icon') > -1) {
    return
  }
  emit('clickItem', item)
}
const handleHistoryAddClick = () => {
  emit('add')
}
const handleDelete = async (item: any) => {
  showConfirmDialog({
    title: '确认',
    message: '是否确认删除该条对话？删除后无法恢复！',
  })
      .then(async () => {
        await AppApi.deleteContext(appId||'', item.id).catch((e) => {
          showFailToast('删除失败:'+e)
        })
        loadData()
      })
      .catch(() => {
        // on cancel
      })
}
onMounted(() => {
})
defineExpose({
  loadData
})
</script>
<style scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.history-list {
  flex: 1;
  overflow-y: auto;
}

.delete-icon {
  color: red;
  font-size: 20px;
  line-height: inherit;
}
</style>
